<script setup lang="ts">
import { Command, Id, Task, Time } from '../model'
import { Delete } from '@element-plus/icons-vue'

defineProps<{
  tasks: Task[]
  commands: readonly Readonly<Command>[]
}>()
const emit = defineEmits<{
  (e: 'add', id: Id): void
  (e: 'update:command', index: number, value: Id): void
  (e: 'update:time', index: number, value: Time): void
  (e: 'delete', index: number): void
}>()

function updateMin(value: number, i: number, old: Time) {
  const t = Time.fromMinSec(value, old.getSec())
  if (t.toPrimary() >= 0) {
    emit('update:time', i, t)
  }
}

function updateSec(value: number, i: number, old: Time) {
  const t = Time.fromMinSec(old.getMin(), value)
  if (t.toPrimary() >= 0) {
    emit('update:time', i, t)
  }
}
</script>

<template>
  <div>
    <slot name="header"></slot>
    <ol>
      <li
        v-for="({ id, time }, i) in tasks"
        class="task"
        @click="$emit('add', id)"
      >
        <span class="name-label">命令名称</span>
        <el-select
          :model-value="id"
          @change="value => $emit('update:command', i, value)"
          class="name"
        >
          <el-option
            v-for="{id, name} in commands"
            :key="id"
            :label="name"
            :value="id"
          />
        </el-select>
        <span class="time-label">执行时刻</span>
        <div class="time">
          <el-input-number
            :model-value="time.getMin()"
            @change="value=>updateMin(value??0,i,time)"
            type="number"
            class="time-input"
          />
          分
          <el-input-number
            :model-value="time.getSec()"
            @change="value=>updateSec(value??0,i,time)"
            type="number"
            class="time-input"
          />
          秒
        </div>
        <span class="delete-item">
          <el-tooltip content="删除">
            <el-button
              class="delete"
              type="danger"
              :icon="Delete"
              @click="$emit('delete', i)"
            />
          </el-tooltip>
        </span>
      </li>
    </ol>
  </div>
</template>

<style scoped>
.task {
  --child-height: 32px;

  display: grid;
  margin: 8px 0;
  padding: 8px 1em;

  grid-template-columns: 4em 1fr 32px;
  grid-gap: 1em;

  border-radius: 4px;
  background-color: #fff;
}

.name, .time {
  height: var(--child-height);
}

.name-label, .time-label {
  line-height: var(--child-height);
}

.time-label, .time {
  grid-row-start: 2;
}

.time-input {
  width: 100px;
}

.delete-item {
  grid-row: 1 / 3;
  grid-column-start: 3;
  display: flex;
  align-items: center;
}

.delete {
  width: 100%;
}
</style>
